package com.loongxun.playwithyou.ui.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.util.ReflectionUtils;
import com.loongxun.playwithyou.util.ToastView;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.util.TextUtils;

/**
 *  更换绑定手机号UI
 * Created by Administrator on 2017/8/18.
 */
public class PhoneChangeActivity extends Activity implements View.OnClickListener{

    //标题
    private TextView tv_top_title,tv_ch_hint_phone,tv_ch_hint,tv_ch_code,tv_ch_confirm;
    private EditText et_ch_phone,et_ch_code;

    private Context context;
    //用户编辑器
    private SharedPreferences share;
    private SharedPreferences.Editor editor;
    private SendRequest send;
    private String user_id,user_phone,phone,code;
    private TimeCount time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_phone_change);
        context = PhoneChangeActivity.this;

        share = context.getSharedPreferences("userInfo", 0);
        editor = share.edit();
        user_id = share.getString("user_id", "");
        user_phone = share.getString("user_phone", "");

        initView();
        time = new TimeCount(60000, 1000);
        if ("".equals(user_phone)) {
            tv_top_title.setText("绑定手机号");
            tv_ch_hint_phone.setVisibility(View.GONE);
            tv_ch_hint.setText("为了您使用便捷，请绑定手机号");
        }else {
            tv_ch_hint_phone.setVisibility(View.VISIBLE);
            tv_ch_hint_phone.setText("当前手机号为：" + user_phone.substring(0, 3) + "****" + user_phone.substring(user_phone.length() - 4, user_phone.length()));
            tv_ch_hint.setText("绑定新手机后，下次登录可使用新手机号登录");
            tv_top_title.setText("更改手机号");
        }
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);

        tv_ch_hint_phone = (TextView) findViewById(R.id.tv_ch_hint_phone);
        tv_ch_hint = (TextView) findViewById(R.id.tv_ch_hint);
        et_ch_phone = (EditText) findViewById(R.id.et_ch_phone);
        et_ch_code = (EditText) findViewById(R.id.et_ch_code);
        tv_ch_code = (TextView) findViewById(R.id.tv_ch_code);
        tv_ch_code.setOnClickListener(this);
        tv_ch_confirm = (TextView) findViewById(R.id.tv_ch_confirm);
        tv_ch_confirm.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        ToastView toast;
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_ch_code:
                phone = et_ch_phone.getText().toString().trim();
                if(TextUtils.isEmpty(phone)){
                    toast = new ToastView(context, "请输入手机号");
                    toast.show();
                }else if (!ReflectionUtils.isPhone(phone)) {
                    toast = new ToastView(context, "手机号格式错误，请重新输入");
                    toast.show();
                }else {
                    try {
                        time.start();// 开始计时
                        send = new SendRequest();
                        send.phone = phone;
                        //发送验证码
                        nHttpClient.getAll(ApiInterface.LOGIN_PHONE, send.toSignupPhoneJson().toString(), signupPhoneHandler);
                    } catch (JSONException e) {
                        toast = new ToastView(context, "参数错误");
                        toast.show();
                    }
                }
                break;
            case R.id.tv_ch_confirm:
                phone = et_ch_phone.getText().toString().trim();
                code = et_ch_code.getText().toString().trim();
                if (TextUtils.isEmpty(phone)){
                    toast = new ToastView(context, "请输入手机号");
                    toast.show();
                }else if (!ReflectionUtils.isPhone(phone)) {
                    toast = new ToastView(context, "手机号格式错误，请重新输入");
                    toast.show();
                }else if (TextUtils.isEmpty(getSessionId())) {
                    toast = new ToastView(context, "验证码失效");
                    toast.show();
                }else if(!isCaptcha(code)) {
                    toast = new ToastView(context, "验证码错误");
                    toast.show();
                }else {
                    try {
                        send = new SendRequest();
                        send.userId = user_id;
                        send.phone = phone;
                        send.code = code;
                        send.sessionId = getSessionId();
                        //绑定手机号
                        nHttpClient.getAll(ApiInterface.BIND_PHONE, send.bindPhoneJson().toString(), bindPhoneHandler);
                    } catch (JSONException e) {
                        toast = new ToastView(context, "参数错误");
                        toast.show();
                    }
                }
                break;
            default:
                break;
        }
    }

    public String getSessionId(){
        SharedPreferences shared = getSharedPreferences("userInfo", 0);
        String sessionId = shared.getString("sessionId","");
        return sessionId;
    }

    public boolean isCaptcha(String captcha){
        SharedPreferences shared = getSharedPreferences("userInfo", 0);
        String spCaptcha = shared.getString("code", "");
        if (captcha.equalsIgnoreCase(spCaptcha)){
            return true;
        }else {
            return false;
        }
    }

    private MyHttpClientRespenseHandler bindPhoneHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                new ToastView(context, "手机号绑定成功").show();
                editor.putString("sessionId", "");
                editor.putString("code", "");
                editor.putString("user_phone", phone);
                editor.commit();//提交修改
                CloseKeyBoard();
                finish();
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler signupPhoneHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                try {
                    editor.putString("sessionId", json.getJSONObject("data").getString("sessionId"));
                    editor.putString("code", json.getJSONObject("data").getString("code"));
                    editor.commit();//提交修改
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            tv_ch_code.setClickable(false);//防止重复点击
            tv_ch_code.setText(millisUntilFinished / 1000 + "秒后重新获取");
        }

        @Override
        public void onFinish() {// 计时完毕
            tv_ch_code.setText("点击获取验证码");
            tv_ch_code.setClickable(true);
        }
    }

    // 关闭键盘
    public void CloseKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_ch_code.getWindowToken(), 0);
    }
}
